<?php

namespace app\common\libs;

/**
 * 获取经纬度
 */
class GetLatAndLon
{

    //城市
    protected string $city = '';

    //县区
    protected string $address = '';

    //url
    protected string $url = 'http://api.map.baidu.com/geocoding/v3/?output=json&output=json&address=%s&city=%s&ak=%s';

    //key
    protected string $key = 'j6d2zTfenprZIo4mWigRUfUr4oxnXCf1';

    protected static $_Instance = null;

    /**
     * 转换地址经纬度
     */
    public static function getInstance()
    {
        if (empty(self::$_Instance)) {
            self::$_Instance = new static;
        }

        return self::$_Instance;
    }

    //城市
    public function setCity($city = '')
    {
        $this->city = $city;
        return $this;
    }

    //县区
    public function setAddress($address = '')
    {
        $this->address = $address;
        return $this;
    }

    //转换位置
    public function sendLatAanLon(): ?array
    {
        $array  =  $this->chackeData();
        if (empty($array)){
            return null;
        }
        $data = json_decode(file_get_contents(sprintf($this->url, $array['address'], $array['city'], $this->key)), true, 512, JSON_THROW_ON_ERROR);
        if (!empty($data) && (int)$data['status'] === 0) {
            $result['lat'] = $data['result']['location']['lat'];
            $result['lng'] = $data['result']['location']['lng'];
            return $result;
        }
        return null;

    }

    //验证
    private function chackeData()
    {
        if (empty($this->address) || empty($this->city)) {
            return null;
        }
        if (!preg_match("/^[\x7f-\xff]+$/", $this->city)) {
            return null;
        }
        if (!preg_match("/^[\x7f-\xff]+$/", $this->address)) {
            return null;
        }
        return ['city' => $this->city, 'address' => $this->address];
    }
}